package org.jeecg.modules.demo.reserverecord.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.reserverecord.entity.ReserveRecord;
import org.jeecg.modules.demo.reserverecord.service.IReserveRecordService;
import org.jeecg.modules.demo.storeemplee.entity.StoreEmplee;
import org.jeecg.modules.demo.storeemplee.service.IStoreEmpleeService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.storeproject.entity.StoreProject;
import org.jeecg.modules.demo.storeproject.service.IStoreProjectService;
import org.jeecg.modules.util.*;
import org.jeecg.modules.weixin.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @Description: 预约
 * @Author: jeecg-boot
 * @Date: 2022-01-14
 * @Version: V1.0
 */
@Api(tags = "预约")
@RestController
@RequestMapping("/reserverecord/reserveRecord")
@Slf4j
public class ReserveRecordController extends JeecgController<ReserveRecord, IReserveRecordService> {
    @Autowired
    private IReserveRecordService reserveRecordService;
    @Autowired
    private IStoreProjectService storeProjectService;
    @Autowired
    private IStoreEmpleeService storeEmpleeService;

    @Autowired
    private IStoreInfoService storeInfoService;
    @Autowired
    private IMsgTemplateService msgTemplateListService;
    @Autowired
    private IMemberManagementService memberManagementService;


    @Autowired
    private RedisUtils redisUtils;


    /**
     * 分页列表查询
     *
     * @param reserveRecord
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "预约-分页列表查询")
    @ApiOperation(value = "0515预约-分页列表查询", notes = "预约-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ReserveRecord reserveRecord,
                                   @RequestParam(name = "startDate", defaultValue = "") String startDate,
                                   @RequestParam(name = "endDate", defaultValue = "") String endDate,
                                   @RequestParam(name = "sortArg", defaultValue = "") String sortArg,
                                   @RequestParam(name = "seqNo", defaultValue = "") String seqNo,
                                   @RequestParam(name = "orderStatus", defaultValue = "") String orderStatus,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<ReserveRecord> queryWrapper = new QueryWrapper<ReserveRecord>();
        queryWrapper.eq("store_id", storeId)
                .like(StringUtils.isNotEmpty(reserveRecord.getMemberName()), "member_name", reserveRecord.getMemberName())
                .like(StringUtils.isNotEmpty(reserveRecord.getCellphone()), "cellphone", reserveRecord.getCellphone())
                .like(StringUtils.isNotEmpty(reserveRecord.getOrderNo()), "order_no", reserveRecord.getOrderNo());
        //.orderByDesc("create_time");
        queryWrapper.and(StringUtils.isNotEmpty(startDate),i ->
                i.and(t ->t.ge(StringUtils.isNotEmpty(startDate), "order_date", startDate).le(StringUtils.isNotEmpty(startDate), "order_date", endDate))
                .or(t -> t.ge(StringUtils.isNotEmpty(startDate), "create_time", startDate+" 00:00:00").le(StringUtils.isNotEmpty(startDate), "create_time", endDate+" 23:59:59"))
        );

        if (!StringUtils.isBlank(sortArg) && !StringUtils.isBlank(seqNo)) {
            if (sortArg.equals("create")) {
                queryWrapper.orderBy(true, seqNo.equals("asc"), "create_time");
            } else {
                queryWrapper.orderBy(true, seqNo.equals("asc"), "prebook_time");
            }
        } else {
            if (orderStatus.equalsIgnoreCase("W")) {
                queryWrapper.orderBy(true, true, "create_time");
            }
            if (orderStatus.equalsIgnoreCase("W")) {
                queryWrapper.orderBy(true, true, "order_date");
            }
            if (orderStatus.equalsIgnoreCase("W")) {
                queryWrapper.orderByDesc("create_time");
            }
        }

        QueryGenerator.initQueryWrapper(queryWrapper, reserveRecord, req.getParameterMap());
        Page<ReserveRecord> page = new Page<ReserveRecord>(pageNo, pageSize);
        IPage<ReserveRecord> pageList = reserveRecordService.page(page, queryWrapper);

        List<Map> maps = new ArrayList<>();
        for (ReserveRecord r : pageList.getRecords()) {
            Map<String, Object> map = BeanUtils.bean2Map(r);


            List<StoreProject> list = storeProjectService.list(new QueryWrapper<StoreProject>().eq("store_id", r.getStoreId()).eq("id", r.getProjectId()));
            if (list.size() > 0) {
                StoreProject storeProject = list.get(0);
                map.put("projectName", storeProject.getName());
            }
            List<StoreEmplee> list1 = storeEmpleeService.list(new QueryWrapper<StoreEmplee>().eq("store_id", r.getStoreId()).eq("id", r.getStaffId()));
            if (list1.size() > 0) {
                StoreEmplee emplee = list1.get(0);
                map.put("staffName", emplee.getName());
            } else {
                map.put("staffName", "到店指派");
            }
//            String orderDate = r.getOrderDate() +"("+r.getReserveTime()+")";
//            map.put("orderDate",orderDate);
            maps.add(map);
        }
        Map<String, Object> result = BeanUtils.bean2Map(pageList);
        result.put("records", maps);
        return Result.OK(result);
    }

    /**
     * 添加
     *
     * @param reserveRecord
     * @return
     */
    @AutoLog(value = "预约-添加")
    @ApiOperation(value = "预约-添加", notes = "预约-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ReserveRecord reserveRecord, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        reserveRecord.setStoreId(storeId);

        if (reserveRecord.getOrderNo() == null) {
            reserveRecord.setOrderNo(ToolsUtils.getBillNo("YY"));
        }
        if (reserveRecord.getPrebookTime() == null) {
            int startHours = getStartHours(reserveRecord.getReserveTime());
            LocalDateTime of = LocalDateTime.of(reserveRecord.getOrderDate(), LocalTime.of(startHours, 0));

            reserveRecord.setPrebookTime(DateUtils.local2util(of));
        }
        reserveRecordService.save(reserveRecord);

        return Result.OK("添加成功！");
    }

    private int getStartHours(String rTime) {
        if (rTime == null) {
            return 0;
        }
        String[] split = rTime.split(":");
        if (split.length == 1 || split.length == 2 || split.length == 3) {
            return Integer.valueOf(split[0]);
        }

        return 0;
    }

    /**
     * 编辑
     *
     * @param reserveRecord
     * @return
     */
    @AutoLog(value = "预约-编辑")
    @ApiOperation(value = "预约-编辑", notes = "预约-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> edit(@RequestBody ReserveRecord reserveRecord, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        ReserveRecord record = reserveRecordService.getById(reserveRecord.getId());
        StoreInfo store = storeInfoService.getById(storeId);

        boolean flag = true;
        if (store == null) {
            log.info("发送预约审核消息失败，未查到店铺信息");
            flag = false;
        }
        String appId = "";
        String appSecret = "";
        String gzhAppId = store.getGzhAppId();
        String gzhAppSecret = store.getGzhAppSecret();
        String xcxAppId = store.getXcxAppId();
        String xcxAppSecret = store.getXcxAppSecret();

        appId = gzhAppId;
        appSecret = gzhAppSecret;
        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
            log.info("发送预约审核消息失败，店铺未绑定公众号");
            flag = false;
        }
//        if (StringUtils.isEmpty(xcxAppId) || StringUtils.isEmpty(xcxAppSecret)) {
//            log.info("发送预约审核消息失败，店铺未绑定公众号");
//            flag = false;
//        }

        String memberId = record.getMemberId();
        MemberManagement member = memberManagementService.getById(memberId);
        String userGzhOpenId = member.getGzhOpenId();

        String xcxOpenId = member.getXcxOpenId();
        String openId = userGzhOpenId;
        if (StringUtils.isEmpty(userGzhOpenId)) {
            log.info("发送预约审核消息失败，未获得会员的公众号openId");
            flag = false;
        }
//        if (StringUtils.isEmpty(xcxOpenId) ) {
//            log.info("发送预约审核消息失败，未获得会员的公众号openId");
//            flag = false;
//        }


        if (flag) {
            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String result1 = HttpUtils.sendGet(url1);
            JSONObject resultJson1 = JSON.parseObject(result1);
            String errcode = resultJson1.getString("errcode");
            if (errcode != null && !"0".equals(errcode)) {
                log.info("发送预约审核消息失败，获取accessToken返回值异常，错误码：{}", errcode);
            }
            String accessToken = resultJson1.getString("access_token");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
            String projectId = record.getProjectId();
            String projectName = "";
            if (!StringUtils.isBlank(projectId)) {
                StoreProject project = storeProjectService.getById(projectId);
                projectName = project.getName();
            }
            List<String> list = new ArrayList<>();
            list.add(record.getMemberName());
            String yuyueTime = record.getOrderDate() + " " + record.getReserveTime();
            list.add(yuyueTime);
            list.add(projectName);
            String result = reserveRecord.getStatus().equals("1") ? "审核通过" : "申请被拒绝";
            MsgTemplate msgTemplate = msgTemplateListService.getByTitle("预约处理提醒", store.getId());
            String templateId = msgTemplate.getTemplateId();
            util.prebookResultNotice(templateId, openId, list, result, sdf.format(new Date()), xcxAppId, "", accessToken);
            log.info("预约处理推送成功");
        }
        reserveRecordService.updateById(reserveRecord);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "充值卡费用设置-通过id删除")
    @ApiOperation(value = "充值卡费用设置-通过id删除", notes = "充值卡费用设置-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }


        reserveRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "充值卡费用设置-批量删除")
    @ApiOperation(value = "充值卡费用设置-批量删除", notes = "充值卡费用设置-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.reserveRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "充值卡费用设置-通过id查询")
    @ApiOperation(value = "充值卡费用设置-通过id查询", notes = "充值卡费用设置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ReserveRecord reserveRecord = reserveRecordService.getById(id);
        if (reserveRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(reserveRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param reserveRecord
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ReserveRecord reserveRecord) {
        return super.exportXls(request, reserveRecord, ReserveRecord.class, "充值卡费用设置");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ReserveRecord.class);
    }

}
